package com.amigo.online.provider.search.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import com.amigo.online.common.param.dto.query.Searchparam;

@Aspect
@Component
public class EscapeQueryCharsAspect {

    //	@Pointcut("@within(com.amigo.online.provider.search.aspect.EscapeQueryChars)")
//	public void aspect() {
//	}
    @Before("@annotation(com.amigo.online.provider.search.aspect.EscapeQueryChars)")
    public void before(JoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        if (args.length > 0 && args[0] instanceof Searchparam) {
            Searchparam searchParam = (Searchparam) args[0];
            //solr中索引存储的都是小写的
            searchParam.setQ(escapeQueryChars(searchParam.getQ()).toLowerCase());
        }
    }


    public String escapeQueryChars(String s) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            // These characters are part of the query syntax and must be escaped
            if (c == '\\' || c == '+' || c == '-' || c == '!' || c == '(' || c == ')' || c == ':'
                    || c == '^' || c == '[' || c == ']' || c == '\"' || c == '{' || c == '}' || c == '~'
                    || c == '*' || c == '?' || c == '|' || c == '&' || c == ';' || c == '/'
                    || Character.isWhitespace(c)) {
                sb.append('\\');
            }
            sb.append(c);
        }
        return sb.toString();
    }
}
